package com.fh.area.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.fh.area.entity.po.Area;
import com.fh.area.mapper.AreaMapping;
import com.fh.area.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 宋闯胜
 * @PackageName:com.fh.service.impl
 * @ClassName: AreaService
 * @Description:
 * @date 2021/11/10 13:39
 */
@Service
public class AreaServiceImpl implements AreaService {
    private StringBuffer stringBuffer ;
    @Resource
    private AreaMapping areaMapping;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String queryAreaData() {
        //[{value:"bj",label:"北京",children:[]}],
        List<Area> areaList = areaMapping.queryArea();
        stringBuffer = new StringBuffer("[");
        int count=0;
        for (int i = 0; i <areaList.size(); i++) {

            Area area = areaList.get(i);
            if (area.getPid()!=null&&area.getPid()==0){
                count++;
                stringBuffer.append("{");
                stringBuffer.append("\"value\":");
                stringBuffer.append(area.getId());
                stringBuffer.append(",\"label\":\"");
                stringBuffer.append(area.getName());
                childrenTree(area.getId(),areaList);
                stringBuffer.append("},");
            }
        }
        String s = stringBuffer.substring(0, stringBuffer.length() - 1) + "]";
        redisTemplate.opsForValue().set("area",s);
        return s;
    }



    private void childrenTree(Integer id, List<Area> areaList) {
        stringBuffer.append("\",\"children\":[");
        int count=0;
        for (int i = 0; i <areaList.size() ; i++) {
            Area list = areaList.get(i);
            if (list.getPid()!=null&&list.getPid().equals(id)){
                count++;
                stringBuffer.append("{\"value\":");
                stringBuffer.append(list.getId());
                stringBuffer.append(",\"label\":\"");
                stringBuffer.append(list.getName());
                childrenTree(list.getId(),areaList);
                stringBuffer.append("},");
            }}if(count>0){
            stringBuffer.replace(stringBuffer.length()-1,stringBuffer.length(),"]");
        }else{
            stringBuffer.replace(stringBuffer.length()-13,stringBuffer.length(),"");
        }
    }
}
